package yxy.game.pm2.module.union.war;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import com.alibaba.fastjson.JSON;
import org.joda.time.DateTime;

import yxy.apple.logger.Logger;
import yxy.apple.util.concurrent.ThreadPoolManager;
import yxy.cherry.battle.Team;
import yxy.cherry.battle.module.record.result.BattleResult;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.unionfight;
import yxy.cherry.data.bean.unionfightbuff;
import yxy.cherry.data.string.GameString;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.Format.FormatType;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.bean.area.AreaGroupBean;
import yxy.game.pm2.bean.cluster.ClusterBean;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.bean.task.TaskType;
import yxy.game.pm2.message.BattleMessage;
import yxy.game.pm2.message.HeroMessage;
import yxy.game.pm2.message.UnionWarMessage;
import yxy.game.pm2.message.UnionWarMessage.UnionWarState;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.battle.BattleHandle;
import yxy.game.pm2.module.battle.BattleModule;
import yxy.game.pm2.module.battle.BattleRecord;
import yxy.game.pm2.module.battle.BattleType;
import yxy.game.pm2.module.battle.FighterModule;
import yxy.game.pm2.module.battle.TeamModule;
import yxy.game.pm2.module.task.TaskHandle;
import yxy.game.pm2.module.union.UnionBean;
import yxy.game.pm2.module.union.player.UnionPlayer;
import yxy.game.pm2.module.union.rank.RankActiveUnion;
import yxy.game.pm2.module.union.rank.RankAreaGroupActiveUnion;

public class UnionWarHandle {
	protected static Logger logger = Logger.create(UnionWarHandle.class);

	static public enum UnionWarStateEnum {
		TRUCE(0), // 停战中
		WAR(1), // 开战中
		SETTLE(2), // 结算中
		BYE(4), // 未匹配或轮空
		;

		private int number;

		private UnionWarStateEnum(int number) {
			this.number = number;
		}

		public int getNumber() {
			return number;
		}
	}

	static private UnionWarStateEnum state(DateTime time) {
		if (time == null) {
			return UnionWarStateEnum.TRUCE;
		}
		int week = time.getDayOfWeek();// 星期
		switch (week) {
		case 1:
		case 3:
		case 5: {
			if (time.getHourOfDay() < 12) {
				return UnionWarStateEnum.TRUCE;
			}
			if (time.getHourOfDay() >= 20) {
				return UnionWarStateEnum.SETTLE;
			}
			return UnionWarStateEnum.WAR;
		}
		}
		return UnionWarStateEnum.TRUCE;
	}

	// XXX TEST 短时测试
//	static private UnionWarStateEnum state(DateTime time) {
//		if (time == null) {
//			return UnionWarStateEnum.TRUCE;
//		}
////		int minute = time.getMinuteOfHour();
////		if (minute < 5) {
////			return UnionWarStateEnum.TRUCE;
////		}
////		if (minute < 55) {
////			return UnionWarStateEnum.WAR;
////		}
////		return UnionWarStateEnum.SETTLE;
//
//		if (time.getHourOfDay() < 12) {
//			return UnionWarStateEnum.TRUCE;
//		}
//		if (time.getHourOfDay() >= 20) {
//			return UnionWarStateEnum.SETTLE;
//		}
//		return UnionWarStateEnum.WAR;
//	}

	/** 状态更新 */
	public void update() {
		Collection<AreaGroupBean> areaGroupBeans = AreaGroupBean.all(); //战区列表
		logger.info("联盟战状态:战区%s", JSON.toJSONString(areaGroupBeans));
		for (AreaGroupBean areaGroupBean : areaGroupBeans) {
			int areaGroupId = areaGroupBean.getGroupId();
			logger.info("联盟战状态1:战区%s", areaGroupId);

			RedisLock lock = UnionWarModule.lock(areaGroupId);
			try {
				if (lock.tryLock()) {
					logger.info("联盟战状态2:战区%s", areaGroupId);
					DateTime now = DateTime.now();
					UnionWarModule module = UnionWarModule.get(areaGroupId);
					UnionWarStateEnum preState = state(module.getUpdateTime());
					UnionWarStateEnum nowState = state(now);
					logger.info("联盟战状态:战区%s:%s:%s", areaGroupId, preState, nowState);
					if (preState.equals(nowState)) {
						continue;
					}

					module.setUpdateTime(now);
					switch (nowState) {
						case TRUCE:
							module.getUnionSet().clear();
							break;
						case WAR:
							// 筛选联盟保存快照
							war(module, now);
							break;
						case SETTLE:
							// 派发邮件奖励
							ThreadPoolManager.getInstance().execute(new Runnable() {
								@Override
								public void run() {
									settle(module);
								}
							});
							break;
						default:
							break;
					}
					module.setState(nowState);
					logger.info("联盟战更新状态:战区%s:%s", areaGroupId, nowState);
					module.set();
				}
			} catch (Exception e) {
				logger.error("联盟战状态:战区%s", areaGroupId);
				logger.error("联盟战状态:战区%s", e);
				e.printStackTrace();
			} finally {
				try {
					lock.unlock();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	static private int LIMIT_ActiveDay = -1; // 选取活跃天数在此数值内的联盟 <0表示不设限
	static private int LIMIT_UnionLevel = 1; // 可参赛等级
	static private int LIMIT_Member = 1;// @TODO:最低参赛人数 原值：10

	//开赛初始化
	private void war(UnionWarModule unionWarModule, DateTime now) {
		logger.info("联盟战状态:war");
		unionWarModule.getUnionSet().clear();
		unionWarModule.getGroups().clear();

		AreaGroupBean areaGroupBean = AreaGroupBean.get(unionWarModule.getAreaGroupId());
		RankAreaGroupActiveUnion rank = new RankAreaGroupActiveUnion(areaGroupBean); //战区内的排行

		Collection<RankEntry> range = null;
		if (LIMIT_ActiveDay < 0) {
			range = rank.range(1, 0);
		} else {
			RankEntry topEntry = rank.entryByRanking(1);
			range = rank.range(now.minusDays(LIMIT_ActiveDay).getMillis(), topEntry.getValue());
		}
		logger.info("联盟战状态:war:rank %s", JSON.toJSONString(range));
		ArrayList<UnionWarUnionModule> list = new ArrayList<>();
		for (RankEntry entry : range) {
			UnionBean unionBean = UnionBean.get(entry.getKey());
			logger.info("联盟战:联盟 %s:等级 %s:人数 %s", unionBean.getCode(), unionBean.getLevel(), unionBean.members().size());
			if (unionBean == null || unionBean.getLevel() < LIMIT_UnionLevel || unionBean.members().size() < LIMIT_Member) {
				continue;// 没有参赛资格
			}
			// 挂锁
			UnionWarUnionModule warModule = UnionWarUnionModule.create(unionBean);
			list.add(warModule);
		}
		// 不需要打乱，就按照最后活跃时间排行分配
		// Collections.shuffle(list);
		for (int i = 0; i < list.size(); i += 2) {
			if (i + 1 >= list.size()) {
				break;
			}
			UnionWarUnionModule unionA = list.get(i);
			UnionWarUnionModule unionB = list.get(i + 1);
			unionA.setOppoUnionCode(unionB.getUnionCode());
			unionB.setOppoUnionCode(unionA.getUnionCode());

			new RankUnionWar(unionA.getUnionCode()).clear();
			new RankUnionWar(unionB.getUnionCode()).clear();

			UnionWarGroup group = new UnionWarGroup();
			group.setUnionA(unionA.getUnionCode());
			group.setUnionB(unionB.getUnionCode());
			unionWarModule.getGroups().add(group);
			unionWarModule.getUnionSet().add(unionA.getUnionCode());
			unionWarModule.getUnionSet().add(unionB.getUnionCode());

			unionA.set();
			unionB.set();
		}
	}

	private void settle(UnionWarModule unionWarModule) {
		for (UnionWarGroup group : unionWarModule.getGroups()) {
			UnionWarUnionModule unionA = UnionWarUnionModule.get(group.getUnionA());
			UnionWarUnionModule unionB = UnionWarUnionModule.get(group.getUnionB());
			handleWin(unionA, unionB);
			unionA.settle();
			unionB.settle();
			unionA.set();
			unionB.set();

			if (unionA.isWin()) {
				for (String playerCode : unionA.getEntrySet()) {
					TaskHandle.handle(playerCode, TaskType.统计型_联盟战_联盟胜利_次数, 1);
				}
			}
			if (unionB.isWin()) {
				for (String playerCode : unionB.getEntrySet()) {
					TaskHandle.handle(playerCode, TaskType.统计型_联盟战_联盟胜利_次数, 1);
				}
			}
		}
	}

	private void handleWin(UnionWarUnionModule unionA, UnionWarUnionModule unionB) {
		int starA = unionA.star();
		int starB = unionB.star();
		if (starA > starB) {
			unionA.setWin(true);
			return;
		}
		if (starA < starB) {
			unionB.setWin(true);
			return;
		}
		long scoreA = unionA.totalScore();
		long scoreB = unionB.totalScore();
		if (scoreA > scoreB) {
			unionA.setWin(true);
			return;
		}
		if (scoreA < scoreB) {
			unionB.setWin(true);
			return;
		}
	}

	// func==========================================================================

	public Result warInfo(String playerCode, UnionBean union, UnionWarMessage.UnionWarResponse.Builder response) {
		ServerBean serverBean = ServerBean.get(union.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		AreaGroupBean areaGroupBean = AreaGroupBean.get(areaBean.getGroupId());
		ClusterBean clusterBean = ClusterBean.get(areaBean.getClusterId());

		DateTime now = DateTime.now();
		UnionWarModule module = UnionWarModule.get(areaGroupBean.getGroupId());
		UnionWarStateEnum state = module.getState();

		switch (state) {
		case TRUCE:
			response.setState(UnionWarState.TRUCE);
			return Result.Success;
		case WAR:
		case SETTLE:
			boolean 参赛 = module.getUnionSet().contains(union.getCode());
			if (!参赛) {
				response.setState(UnionWarState.BYE);
				return Result.Success;
			}
		default:
			break;
		}
		UnionWarUnionModule unionA = UnionWarUnionModule.get(union.getCode());
//		if (!unionA.getEntrySet().contains(playerCode)) {
//			response.setState(UnionWarState.BYE);
//			return Result.Success;// 没有参赛资格
//		}
		UnionWarUnionModule unionB = UnionWarUnionModule.get(unionA.getOppoUnionCode());

		response.setState(UnionWarState.forNumber(state.getNumber()));
		{
			UnionWarMessage.UnionWarInfo.Builder builder = UnionWarMessage.UnionWarInfo.newBuilder();
			builder.setName(unionA.getName());
			builder.setLevel(unionA.getLevel());
			builder.setPower(unionA.getPower());
			builder.setStar(unionA.star());
			response.setSelf(builder);
		}
		{
			UnionWarMessage.UnionWarInfo.Builder builder = UnionWarMessage.UnionWarInfo.newBuilder();
			builder.setName(unionB.getName());
			builder.setLevel(unionB.getLevel());
			builder.setPower(unionB.getPower());
			builder.setStar(unionB.star());
			response.setOppo(builder);
		}
		{
			switch (state) {
			case WAR:
				long endTime = now.withTimeAtStartOfDay().plusHours(20).getMillis() - now.getMillis();
				response.setEndtime(endTime < 0 ? 0 : endTime);
				break;
			case SETTLE:
				response.setEndtime(0);
				break;
			default:
				break;
			}
			response.setBuff(unionA.getBuff());
		}
		{
			UnionWarPlayerModule warPlayerModule = UnionWarPlayerModule.get(playerCode);
			response.setTimes(warPlayerModule.getTimes());
		}
		{
			RankUnionWar unionWarRank = new RankUnionWar(union.getCode());
			Collection<RankEntry> top = unionWarRank.top(3);
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int score = entry.getValue().intValue();
				PlayerBean playerBean = PlayerBean.get(pCode);

				UnionWarMessage.TopUnionWar.Builder builder = UnionWarMessage.TopUnionWar.newBuilder();
				builder.setRank(++rank);
				builder.setScore(score);
				builder.setName(playerBean.getName());
				response.addTop(builder);
			}
		}
		{
			for (String fortCode : unionA.getForts()) {
				UnionWarFort fort = UnionWarFort.get(unionA.getUnionCode(), fortCode);
				UnionWarMessage.UnionWarFort.Builder builder = UnionWarMessage.UnionWarFort.newBuilder();
				builder.setCode(fort.getPlayerCode());
				builder.setName(fort.getName());
				builder.setPower(fort.getPower());
				builder.setStar(fort.getStar());
				response.addSelfForts(builder);
			}
		}
		{
			for (String fortCode : unionB.getForts()) {
				UnionWarFort fort = UnionWarFort.get(unionB.getUnionCode(), fortCode);
				UnionWarMessage.UnionWarFort.Builder builder = UnionWarMessage.UnionWarFort.newBuilder();
				builder.setCode(fort.getPlayerCode());
				builder.setName(fort.getName());
				builder.setPower(fort.getPower());
				builder.setStar(fort.getStar());
				response.addOppoForts(builder);
			}
		}

		return Result.Success;
	}

	public Result defenceInfo(String unionCode, String fortCode, UnionWarMessage.UnionWarDefenceLogResponse.Builder response) {
		UnionBean unionBean = UnionBean.get(unionCode);
		ServerBean serverBean = ServerBean.get(unionBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		AreaGroupBean areaGroupBean = AreaGroupBean.get(areaBean.getGroupId());
		ClusterBean clusterBean = ClusterBean.get(areaBean.getClusterId());

		UnionWarModule unionWarModule = UnionWarModule.get(areaGroupBean.getGroupId());
		if (!unionWarModule.getUnionSet().contains(unionCode)) {
			return Result.UnionWarNotIn;// 你的联盟没有参战
		}

		UnionWarFort fort = findFort(unionCode, fortCode);
		if (fort == null) {
			return Result.ParamError;// 据点信息不存在
		}
		response.setFort(fortInfo(fort));

		for (UnionWarRecord record : fort.getRecords()) {
			UnionWarMessage.UnionWarRecord.Builder builder = UnionWarMessage.UnionWarRecord.newBuilder();
			builder.setRecord(record.getRecordCode());
			builder.setDate(record.getDate().getMillis());
			builder.setLevel(record.getStar());
			builder.setSuccess(record.isWin());
			builder.setNickname(record.getNickName());
			builder.setPower(record.getPower());
			for (FighterModule fighter : record.getFighters()) {
				HeroMessage.HeroSimple.Builder heroBuilder = HeroMessage.HeroSimple.newBuilder();
				heroBuilder.setCode("xxx");
				heroBuilder.setDataId(fighter.getHeroId());
				heroBuilder.setLevel(fighter.getLevel());
				heroBuilder.setStar(fighter.getStarlv());
				builder.addHeros(heroBuilder);
			}
			response.addRecords(builder);
		}

		return Result.Success;
	}

	public Result fortInfo(String unionCode, String fortCode, UnionWarMessage.UnionWarFortInfoResponse.Builder response) {
		UnionBean unionBean = UnionBean.get(unionCode);
		ServerBean serverBean = ServerBean.get(unionBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		AreaGroupBean areaGroupBean = AreaGroupBean.get(areaBean.getGroupId());
		ClusterBean clusterBean = ClusterBean.get(areaBean.getClusterId());

		UnionWarModule unionWarModule = UnionWarModule.get(areaGroupBean.getGroupId());
		if (!unionWarModule.getUnionSet().contains(unionCode)) {
			return Result.UnionWarNotIn;// 你的联盟没有参战
		}

		UnionWarFort fort = findFort(unionCode, fortCode);
		if (fort == null) {
			return Result.ParamError;// 据点信息不存在
		}
		response.setFort(fortInfo(fort));
		return Result.Success;
	}

	private UnionWarMessage.UnionWarFort fortInfo(UnionWarFort fort) {
		UnionWarMessage.UnionWarFort.Builder builder = UnionWarMessage.UnionWarFort.newBuilder();
		// 据点信息
		builder.setCode(fort.getPlayerCode());
		builder.setName(fort.getName());
		builder.setPower(fort.getPower());
		builder.setStar(fort.getStar());
		TeamModule team = fort.getTeam();
		for (FighterModule fighter : team.fighters().values()) {
			HeroMessage.HeroSimple.Builder heroBuilder = HeroMessage.HeroSimple.newBuilder();
			heroBuilder.setCode("xxx");
			heroBuilder.setDataId(fighter.getHeroId());
			heroBuilder.setLevel(fighter.getLevel());
			heroBuilder.setStar(fighter.getStarlv());
			builder.addHeros(heroBuilder);
		}
		return builder.build();
	}

	private UnionWarFort findFort(String unionCode, String fortCode) {
		UnionWarUnionModule unionA = UnionWarUnionModule.get(unionCode);
		if (unionA.getForts().contains(fortCode)) {
			UnionWarFort fort = UnionWarFort.get(unionA.getUnionCode(), fortCode);
			return fort;
		}
		UnionWarUnionModule unionB = UnionWarUnionModule.get(unionA.getOppoUnionCode());
		if (unionB.getForts().contains(fortCode)) {
			UnionWarFort fort = UnionWarFort.get(unionB.getUnionCode(), fortCode);
			return fort;
		}
		return null;
	}

	public Result battleResponseExecute(String playerCode, UnionBean union, String fortCode, int star,
			UnionWarMessage.UnionWarChanllengeResponse.Builder response) {

		ServerBean serverBean = ServerBean.get(union.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		AreaGroupBean areaGroupBean = AreaGroupBean.get(areaBean.getGroupId());
		ClusterBean clusterBean = ClusterBean.get(areaBean.getClusterId());

		UnionWarModule unionWarModule = UnionWarModule.get(areaGroupBean.getGroupId());
		if (!unionWarModule.getState().equals(UnionWarStateEnum.WAR)) {
			return Result.UnionWarSettled;// 联盟战已经结束
		}
		if (!unionWarModule.getUnionSet().contains(union.getCode())) {
			return Result.UnionWarNotIn;// 你的联盟没有参战
		}

		UnionWarUnionModule unionA = UnionWarUnionModule.get(union.getCode());
		UnionWarUnionModule unionB = UnionWarUnionModule.get(unionA.getOppoUnionCode());

		RedisLock fLock = UnionWarFort.lock(unionB.getUnionCode());
		RedisLock pLock = UnionWarPlayerModule.lock(playerCode);
		try {
			if (fLock.tryLock() && pLock.tryLock()) {

				UnionWarPlayerModule unionWarPlayerModule = UnionWarPlayerModule.get(playerCode);
				if (unionWarPlayerModule.times() <= 0) {
					return Result.UnionWarTimesOut;// 你没有次数了
				}

				if (!unionB.getForts().contains(fortCode)) {
					return Result.ParamError;// 据点信息不存在
				}
				UnionWarFort fort = UnionWarFort.get(unionB.getUnionCode(), fortCode);
				if (fort == null) {
					return Result.ParamError;// 据点信息不存在
				}
				if (fort.getStar() + star > 3) {
					return Result.UnionWarStarOut;// 该难度不能挑战
				}
				DateTime now = DateTime.now();
				int index = fort.getIndex();
				unionfight data = DataCenter.getData(index, unionfight.class);

				int diff = data.getDifficulty1()[(star <= 1 ? 1 : star) - 1];// 难度控制
				int buff = unionA.getBuff();// 增益buff
				unionfightbuff buffdata = DataCenter.getData(buff, unionfightbuff.class);

				BattleHandle battleHandle = new BattleHandle();

				BattleModule battleModule = BattleModule.create(playerCode);
				battleModule.setType(BattleType.UNIONFIGHT);
				battleModule.setCode(BattleType.UNIONFIGHT.name());

				// 玩家的team
				TeamModule teamA = battleHandle.teamPlayer(playerCode, FormatType.普通);
				for (FighterModule fighter : teamA.fighters().values()) {
					fighter.getProperty().setAtt(fighter.getProperty().getAtt() + fighter.getProperty().getAtt() * buffdata.getAttack() / 10000);
					fighter.getProperty().setPdef(fighter.getProperty().getPdef() + fighter.getProperty().getPdef() * buffdata.getPdefense() / 10000);
					fighter.getProperty().setSefe(fighter.getProperty().getSefe() + fighter.getProperty().getSefe() * buffdata.getSefense() / 10000);
					fighter.getProperty().setLife(fighter.getProperty().getLife() + fighter.getProperty().getLife() * buffdata.getLife() / 10000);
				}

				battleModule.setTeamA(teamA);

				TeamModule teamB = fort.getTeam();
				for (FighterModule fighter : teamB.fighters().values()) {
					fighter.getProperty().setAtt(fighter.getProperty().getAtt() + fighter.getProperty().getAtt() * diff / 10000);
					fighter.getProperty().setPdef(fighter.getProperty().getPdef() + fighter.getProperty().getPdef() * diff / 10000);
					fighter.getProperty().setSefe(fighter.getProperty().getSefe() + fighter.getProperty().getSefe() * diff / 10000);
					fighter.getProperty().setLife(fighter.getProperty().getLife() + fighter.getProperty().getLife() * diff / 10000);
				}
				battleModule.setTeamB(teamB);

				Team team_a = teamA.team(true);
				Team team_b = teamB.team(false);
				team_a.setTeam对手(team_b);
				team_b.setTeam对手(team_a);

				// 处理战斗
				battleHandle.battleExecute(battleModule, team_a, team_b, 20);

				// 处理结果
				boolean isWin = battleModule.getBattleResult().equals(BattleResult.LEFT_WIN);

				// 处理得分
				ArrayList<Currency> rewards = new ArrayList<>();
				RankUnionWar unionWarRank = new RankUnionWar(union.getCode());
				int score = 0;
				if (isWin) {
					fort.setStar(fort.getStar() + star);
					// 奖励
					rewards.addAll(Currency.create(data.getWinrewardtype(), data.getWinrewardid(), data.getWinrewardnum()));

					// 战绩
					score = data.getStarreward()[star];

					// 加buff
					if (star <= 0) {
						if (DataCenter.getData(buff + 1, unionfightbuff.class) != null) {
							unionA.setBuff(buff + 1);
							unionA.set();
						}
					}
				} else {
					// 奖励
					rewards.add(Currency.create(data.getFailrewardtype(), data.getFailrewardid(), data.getFailrewardnum()));
					// 战绩
					score = data.getStarrewardfail();

				}
				unionWarRank.addAndSet(playerCode, score);
				new CurrencyHandle().addCurrency(playerCode, CCReason.联盟战, rewards);

				// 处理录像
				{
					BattleRecord battleRecord = battleModule.saveRecord(BattleRecord.randomCode(), 1);

					UnionWarRecord record = new UnionWarRecord();
					record.setStar(star);
					record.setWin(isWin);

					record.setPlayerCode(playerCode);
					record.setNickName(teamA.getName());
					record.setPower(teamA.getPower());
					packFighter(record.getFighters(), teamA.getFighter_FU());
					packFighter(record.getFighters(), teamA.getFighter_FM());
					packFighter(record.getFighters(), teamA.getFighter_FD());
					packFighter(record.getFighters(), teamA.getFighter_BU());
					packFighter(record.getFighters(), teamA.getFighter_BM());
					packFighter(record.getFighters(), teamA.getFighter_BD());

					record.setDate(now);
					record.setRecordCode(battleRecord.getCode());

					fort.getRecords().add(record);
				}

				UnionWarFort.set(unionB.getUnionCode(), fort);

				unionWarPlayerModule.setTimes(unionWarPlayerModule.getTimes() + 1);
				if (isWin) {
					unionWarPlayerModule.setStar(unionWarPlayerModule.getStar() + star);
					TaskHandle.handle(playerCode, TaskType.统计型_联盟战_个人胜利_次数, 1);
				}
				unionWarPlayerModule.set();

				// 处理日志
				{
					PlayerBean playerBean = PlayerBean.get(playerCode);
					String text = null;
					if (isWin) {
						switch (star) {
						case 0:
							text = GameString.联盟战没有星日志文字(unionA.getName(), playerBean.getName(), fort.getName(), score).getText();
							break;
						case 1:
							text = GameString.联盟战1星日志文字(unionA.getName(), playerBean.getName(), fort.getName(), score, unionA.star()).getText();
							break;
						case 2:
							text = GameString.联盟战2星日志文字(unionA.getName(), playerBean.getName(), fort.getName(), score, unionA.star()).getText();
							break;
						case 3:
							text = GameString.联盟战3星日志文字(unionA.getName(), playerBean.getName(), fort.getName(), score, unionA.star()).getText();
							break;
						}
					} else {
						text = GameString.联盟战挑战失败日志文字(unionA.getName(), playerBean.getName(), fort.getName()).getText();
					}
					UnionWarLogBean log = new UnionWarLogBean();
					log.setTime(now);
					log.setText(text);
					log.getPlayer().add(playerCode);
					log.getPlayer().add(fort.getPlayerCode());
					unionA.getLogs().add(log);
					unionB.getLogs().add(log);
					unionA.set();
					unionB.set();
				}

				// 封装消息
				{
					BattleMessage.BattleExecuteResponse.Builder builder = BattleMessage.BattleExecuteResponse.newBuilder();
					builder.setPlayback(battleHandle.playback(battleModule));

					response.setBattleResp(builder);// 录像
					response.setBattleResult(battleModule.getBattleResult().getNumber());// 战果

					response.addAllRewards(new CurrencyHandle().packItems(rewards));

					response.setScore(score);
					response.setStar(isWin ? star : 0);

					response.setFighterA(packFighter(playerCode));// 进攻方
					response.setFighterB(packFighter(fort));// 防守方
				}

				return Result.Success;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			fLock.unlock();
			pLock.unlock();
		}
		return Result.DataError;
	}

	public UnionWarMessage.UnionWarFighter.Builder packFighter(String playerCode) {
		UnionWarMessage.UnionWarFighter.Builder builder = UnionWarMessage.UnionWarFighter.newBuilder();
		PlayerBean player = PlayerBean.get(playerCode);
		builder.setNickname(player.getName());
		builder.setHead(player.getHead());
		builder.setHeadFrame(player.getHeadframe());
		builder.setLevel(player.getLevel());
		return builder;
	}

	public UnionWarMessage.UnionWarFighter.Builder packFighter(UnionWarFort fort) {
		UnionWarMessage.UnionWarFighter.Builder builder = UnionWarMessage.UnionWarFighter.newBuilder();
		builder.setNickname(fort.getName());
		builder.setHead(fort.getHead());
		builder.setHeadFrame(fort.getHeadframe());
		builder.setLevel(fort.getLevel());
		return builder;
	}

	private void packFighter(ArrayList<FighterModule> fighters, FighterModule fighter) {
		if (fighter == null) {
			return;
		}
		FighterModule result = new FighterModule();
		result.setHeroId(fighter.getHeroId());
		result.setLevel(fighter.getLevel());
		result.setStarlv(fighter.getStarlv());
		fighters.add(result);
	}

}
